import axios, { Axios, AxiosRequestConfig } from "axios"

const defaults: AxiosRequestConfig = {
    withCredentials: true
}

class Http {
    private axios: Axios;
    constructor(axios: Axios) {
        this.axios = axios
    }
    get<T = any>(url: string, params = {}, config?: AxiosRequestConfig): Promise<HttpResponseData<T>> {
        const requestConfig: AxiosRequestConfig = {
            ...config,
            url,
            params
        }
        return this.axios.request(requestConfig)
    }
    post<T = any,>(url: string, data = {}, config?: AxiosRequestConfig): Promise<HttpResponseData<T>> {
        const requestConfig: AxiosRequestConfig = {
            ...config,
            method: "POST",
            url,
            data
        }
        return this.axios.request(requestConfig)
    }
}

export default function createHttp(config?: AxiosRequestConfig): Http {
    const requestConfig: AxiosRequestConfig = {
        ...config,
        ...defaults
    }
    const axiosInstance = axios.create(requestConfig)
    axiosInstance.interceptors.response.use((response) => {
        return response.data
    }, (error) => {
        return {
            code: error.request.status,
            url: error.config?.url || '',
            method: error.config?.method || '',
            params: error.config?.params || error.config?.data || {}
        } as HttpResponseError
    })
    return new Http(axiosInstance)
}